import 'package:calendar_view/calendar_view.dart';
import 'package:flutter/material.dart';
import 'package:json/json.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_category.dart';
import 'package:schedule_self_client/utils/time_util.dart';

@JsonCodable()
class TaskExecuteRecord {
  final int id;

  final int taskId;

  final String taskName;

  final String startTime;

  final String endTime;

  final TaskCategory? taskCategoryDto;

  static CalendarEventData convert(
      TaskExecuteRecord record, BuildContext context) {
    return CalendarEventData(
      title: record.taskName,
      color: _getColor(record.taskCategoryDto, context),
      date: DateTime.parse(record.startTime),
      startTime: DateTime.parse(record.startTime)
          .add(TimeUtil.getTimeZoneOffsetDuration()),
      endTime: DateTime.parse(record.endTime)
          .add(TimeUtil.getTimeZoneOffsetDuration()),
      titleStyle: Theme.of(context).textTheme.bodyMedium,
    );
  }

  static Color _getColor(TaskCategory? taskCategory, BuildContext context) {
    if (taskCategory == null) {
      return Theme.of(context).colorScheme.primaryContainer;
    }
    return Color(int.parse(taskCategory.color));
  }

  List<TaskExecuteRecord> splitMultipleDays() {
    DateTime startDateTime =
        DateTime.parse(startTime).add(TimeUtil.getTimeZoneOffsetDuration());
    DateTime endDateTime =
        DateTime.parse(endTime).add(TimeUtil.getTimeZoneOffsetDuration());
    if (startDateTime.day != endDateTime.day) {
      List<TaskExecuteRecord> result = [];
      var firstDayMap = toJson();
      firstDayMap.update(
          'endTime',
          (_) => TimeUtil.formatTimeToBackend(DateTime(startDateTime.year,
                  startDateTime.month, startDateTime.day, 23, 59, 59)
              .subtract(TimeUtil.getTimeZoneOffsetDuration())));
      result.add(TaskExecuteRecord.fromJson(firstDayMap));
      var lastDayMap = toJson();
      lastDayMap.update(
          'startTime',
          (_) => TimeUtil.formatTimeToBackend(DateTime(
                  endDateTime.year, endDateTime.month, endDateTime.day, 0, 0, 0)
              .subtract(TimeUtil.getTimeZoneOffsetDuration())));
      result.add(TaskExecuteRecord.fromJson(lastDayMap));
      return result;
    }
    return [this];
  }
}

@JsonCodable()
class TaskExecuteRecordListResp {
  final bool success;

  final String? errCode;

  final String? errMessage;

  final List<TaskExecuteRecord> data;
}
